<template>
  <view class="index-page">
    <!-- 顶部搜索栏 -->
    <!-- <view class="search-bar">
      <view class="search-input-wrapper">
        <u-icon name="search" size="20" color="#999999" />
        <input 
          type="text" 
          placeholder="搜索任务名称或标签"
          placeholder-style="color: #cccccc;"
          class="search-input"
          @tap="navigateToSearch"
        />
      </view>
    </view> -->
    
    <!-- Banner轮播图 -->
    <view class="banner-section" v-if="banners.length > 0">
      <up-swiper 
        :list="banners" 
        mode="dot" 
        :indicator="true"
        indicatorActiveColor="blue"
        :acceleration="true"
        :circular="true"
        indicator-dots 
        autoplay 
        interval="5000"
        duration="500"
        @click="handleBannerClick"
      ></up-swiper>
    </view>
    
    <!-- 任务类型快捷入口 -->
    <view class="quick-entry">
      <up-grid :col="5" :border="false" :showBorder="false">
        <up-grid-item 
          v-for="(item, index) in taskTypes" 
          :key="item.type"
          @click="navigateToTaskList(item.type)"
        >
          <view class="grid-content">
            <view class="entry-icon" :class="item.type + '-tasks'">
              <u-icon :name="item.icon" size="28" :color="item.color" />
            </view>
            <text class="entry-text">{{ item.name }}</text>
          </view>
        </up-grid-item>
      </up-grid>
    </view>
    
    <!-- 推荐任务 -->
    <view class="section-header">
      <text class="section-title">推荐任务</text>
      <text class="section-more" @click="navigateToTaskList('recommend')">更多 ></text>
    </view>
    
    <view class="task-list recommend-tasks" v-if="recommendTasks.length > 0">
      <task-card 
        v-for="task in recommendTasks" 
        :key="task.id" 
        :task="task"
        @detail="navigateToDetail(task.id)"
        @accept="handleClaimTask(task.id)"
        @submit="navigateToSubmit(task.id)"
        @loginRequired="showLoginModal = true"
      ></task-card>
    </view>
    
    <!-- 热门任务 -->
    <view class="section-header">
      <text class="section-title">热门任务</text>
      <text class="section-more" @click="navigateToTaskList('hot')">更多 ></text>
    </view>
    
    <view class="task-list hot-tasks" v-if="hotTasks.length > 0">
      <task-card 
        v-for="task in hotTasks" 
        :key="task.id" 
        :task="task"
        @detail="navigateToDetail(task.id)"
        @accept="handleClaimTask(task.id)"
        @submit="navigateToSubmit(task.id)"
        @loginRequired="showLoginModal = true"
      ></task-card>
    </view>
    
    <!-- 最新任务 -->
    <view class="section-header">
      <text class="section-title">最新任务</text>
      <text class="section-more" @click="navigateToTaskList('newest')">更多 ></text>
    </view>
    
    <view class="task-list newest-tasks" v-if="newestTasks.length > 0">
      <task-card 
        v-for="task in newestTasks" 
        :key="task.id" 
        :task="task"
        @detail="navigateToDetail(task.id)"
        @accept="handleClaimTask(task.id)"
        @submit="navigateToSubmit(task.id)"
        @loginRequired="showLoginModal = true"
      ></task-card>
    </view>
    
    <!-- 空状态 -->
    <view class="empty-state" v-if="!loading && recommendTasks.length === 0 && hotTasks.length === 0 && newestTasks.length === 0">
      <u-icon name="empty" size="80" color="#cccccc" />
      <text class="empty-text">暂无任务</text>
    </view>
    
    <!-- 下拉刷新 -->
    <u-pull-refresh 
      v-model="refreshing"
      @refresh="handleRefresh"
      head-height="60"
      success-text="刷新成功"
    ></u-pull-refresh>
    
    <!-- 登录弹窗 -->
    <login-modal 
      v-model:visible="showLoginModal" 
      @loginSuccess="handleLoginSuccess"
    ></login-modal>
    
    <!-- 加载中 -->
    <u-loading-page v-if="loading" color="#409eff"></u-loading-page>
  </view>
</template>

<script>
import { defineComponent, ref, onMounted } from 'vue';
import { useTaskStore } from '../../store/task.js';
import { useUserStore } from '../../store/user.js';
import TaskCard from '../../components/task-card.vue';
import LoginModal from '../../components/login-modal.vue';
import taskMock from '../../api/taskMock.js';

export default defineComponent({
  name: 'IndexPage',
  components: {
    TaskCard,
    LoginModal
  },
  setup() {
    const taskStore = useTaskStore();
    const userStore = useUserStore();
    
    // 状态管理
    const loading = ref(true);
    const refreshing = ref(false);
    const showLoginModal = ref(false);
    
    // Banner数据
    const banners = ref([
      { 
        url: 'https://s3.bmp.ovh/imgs/2025/07/12/83e18f93156e578d.png',
        link: '/pages/video/check-video', 
        title: '视频任务'
      },
      { 
        url: 'https://s3.bmp.ovh/imgs/2025/07/12/83e18f93156e578d.png',
        link: '/pages/video/check-video', 
        title: '新手任务'
      },
      { 
        url: 'https://s3.bmp.ovh/imgs/2025/08/15/390558a64937cf3a.png',
        link: '/pages/video/check-video', 
        title: '每日签到'
      },
      { 
        url: 'https://s3.bmp.ovh/imgs/2025/03/21/d8f6a5f813e58a7b.png',
        link: '/pages/video/check-video', 
        title: '积分兑换'
      },{ 
        url: 'https://s3.bmp.ovh/imgs/2025/03/29/fa552900e8c49ef5.jpg',
        link: '/pages/video/check-video', 
        title: '推广'
      }
    ]);
    
    // 任务类型数据（支持后台配置）
    const taskTypes = ref([
      { type: 'video', name: '视频任务', icon: 'list', color: '#409eff' },
      { type: 'pending', name: '新手任务', icon: 'bookmark', color: '#67c23a' },
      { type: 'daily', name: '每日任务', icon: 'calendar', color: '#e6a23c' },
      { type: 'share', name: '分享任务', icon: 'share', color: '#f56c6c' },
      { type: 'survey', name: '调查任务', icon: 'coupon', color: '#909399' }
    ]);
    
    // 任务数据（推荐、热门、最新）
    const recommendTasks = ref([]);
    const hotTasks = ref([]);
    const newestTasks = ref([]);
    
    // 加载首页数据
    const loadHomeData = async () => {
      try {
        loading.value = true;
        
        // 直接使用mock方法获取任务数据，保持与任务列表页面统一的数据源
        const pageSize = 3;
        
        // 推荐任务（可以是混合排序，这里简单使用默认排序）
        let recommendTasksData = taskMock.filterTasks(taskMock.mockTasks);
        recommendTasksData = taskMock.paginateTasks(recommendTasksData, 1, pageSize).list;
        
        // 热门任务（根据完成人数排序）
        let hotTasksData = taskMock.filterTasks(taskMock.mockTasks);
        hotTasksData = taskMock.sortTasks(hotTasksData, 'hottest');
        hotTasksData = taskMock.paginateTasks(hotTasksData, 1, pageSize).list;
        
        // 最新任务（根据创建时间排序）
        let newestTasksData = taskMock.filterTasks(taskMock.mockTasks);
        newestTasksData = taskMock.sortTasks(newestTasksData, 'newest');
        newestTasksData = taskMock.paginateTasks(newestTasksData, 1, pageSize).list;
        
        // 清空之前的数据并更新
        recommendTasks.value = recommendTasksData;
        hotTasks.value = hotTasksData;
        newestTasks.value = newestTasksData;
        
      } catch (error) {
        console.error('加载首页数据失败:', error);
        // 如果发生错误，保持数据不变
      } finally {
        loading.value = false;
        refreshing.value = false;
      }
    };
    
    // 任务数据已通过taskMock.js中的统一mock方法获取
    
    // 处理Banner点击
    const handleBannerClick = (index) => {
      const banner = banners.value[index];
      if (banner.link) {
        // 判断是否为tabBar页面
        const tabBarPages = ['/pages/index/index', '/pages/task-list/task-list', '/pages/video/check-video', '/pages/my/my'];
        const isTabBarPage = tabBarPages.includes(banner.link);
        
        if (isTabBarPage) {
          uni.switchTab({
            url: banner.link
          });
        } else {
          uni.navigateTo({
            url: banner.link
          });
        }
      } else {
        // 根据Banner标题跳转到对应页面
        switch (banner.title) {
          case '新手任务':
            navigateToTaskList('pending');
            break;
          case '每日签到':
            // 跳转到签到页面
            showToast('跳转到签到页面');
            break;
          case '积分兑换':
            // 跳转到兑换页面
            showToast('跳转到积分兑换页面');
            break;
        }
      }
    };
    
    // 处理任务领取
    const handleClaimTask = async (taskId) => {
      // 检查登录状态
      if (!userStore.isLoggedIn) {
        showLoginModal.value = true;
        return;
      }
      
      try {
        const result = await taskStore.claimTask(taskId);
        if (result && result.success) {
          uni.showToast({
            title: '领取成功',
            icon: 'success'
          });
          // 刷新任务列表
          loadHomeData();
        } else {
          uni.showToast({
            title: result.message || '领取失败',
            icon: 'none'
          });
        }
      } catch (error) {
        uni.showToast({
          title: '领取失败，请稍后重试',
          icon: 'none'
        });
      }
    };
    
    // 处理登录成功
    const handleLoginSuccess = () => {
      showLoginModal.value = false;
      // 登录成功后刷新数据
      loadHomeData();
    };
    
    // 导航到搜索页
    const navigateToSearch = () => {
      uni.navigateTo({
        url: '/pages/task-list/task-list?search=true'
      });
    };
    
    // 导航到任务列表
    const navigateToTaskList = (type = 'all') => {
      // 第一部分：视频任务直接跳转到刷视频页面
      if (type === 'video') {
        uni.switchTab({
          url: '/pages/video/check-video'
        });
      } 
      // 第二部分：其他任务跳转到对应分类页面
      else {
        uni.switchTab({
          url: `/pages/task-list/task-list?type=${type}`
        });
      }
    };
    
    // 导航到任务详情
    const navigateToDetail = (taskId) => {
      console.log('index navigateToDetail taskId:', taskId);
      uni.navigateTo({
        url: `/pages/task-detail/task-detail?id=${taskId}`
      });
    };
    
    // 导航到任务提交
    const navigateToSubmit = (taskId) => {
      // 检查登录状态
      if (!userStore.isLoggedIn) {
        showLoginModal.value = true;
        return;
      }
      
      uni.navigateTo({
        url: `/pages/task-submit/task-submit?id=${taskId}`
      });
    };
    
    // 导航到我的页面
    const navigateToMy = () => {
      uni.navigateTo({
        url: '/pages/my/my'
      });
    };
    
    // 下拉刷新
    const handleRefresh = () => {
      refreshing.value = true;
      loadHomeData();
    };
    
    // 简易提示
    const showToast = (title) => {
      uni.showToast({
        title: title,
        icon: 'none',
        duration: 1500
      });
    };
    
    // 生命周期
    onMounted(() => {
      loadHomeData();
    });
    
    return {
      loading,
      refreshing,
      showLoginModal,
      banners,
      taskTypes,
      recommendTasks,
      hotTasks,
      newestTasks,
      handleBannerClick,
      handleClaimTask,
      handleLoginSuccess,
      handleRefresh,
      navigateToSearch,
      navigateToTaskList,
      navigateToDetail,
      navigateToSubmit,
      navigateToMy
    };
  }
});
</script>

<style lang="scss" scoped>
.index-page {
  padding: 16px;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 20px;
}

.search-bar {
  position: sticky;
  top: 0;
  z-index: 10;
  margin-bottom: 16px;
  padding-top: env(safe-area-inset-top);
  padding-bottom: 8px;
  background-color: #f5f5f5;
  
  .search-input-wrapper {
    display: flex;
    align-items: center;
    background-color: #ffffff;
    border-radius: 8px;
    padding: 8px 12px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
    
    .search-input {
      flex: 1;
      border: none;
      outline: none;
      padding: 0 8px;
      font-size: 14px;
      color: #333333;
    }
  }
}

.banner-section {
  margin-bottom: 20px;
  
  :deep() {
    .u-swiper {
      border-radius: 12px;
      overflow: hidden;
      
      .u-swiper-item {
        img {
          width: 100%;
          height: 160px;
          object-fit: cover;
        }
      }
      
      .u-swiper-dots {
        bottom: 12px;
      }
      
      .u-swiper-dot-active {
        background-color: #409eff;
      }
    }
  }
}

.quick-entry {
  background-color: #ffffff;
  border-radius: 12px;
  padding: 16px 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  
  :deep() {
    .up-grid {
      width: 100%;
      
      .up-grid-item {
        padding: 8px 0;
      }
    }
  }
  
  .grid-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 4px 0;
    
    &:active {
      opacity: 0.7;
    }
    
    .entry-icon {
      width: 48px;
      height: 48px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 8px;
      background-color: #f5f5f5;
      
      &.all-tasks {
        background-color: #ecf5ff;
      }
      
      &.pending-tasks {
        background-color: #f0f9eb;
      }
      
      &.daily-tasks {
        background-color: #fdf6ec;
      }
      
      &.share-tasks {
        background-color: #fef0f0;
      }
      
      &.survey-tasks {
        background-color: #f5f7fa;
      }
    }
    
    .entry-text {
      font-size: 12px;
      color: #666666;
    }
  }
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  margin-top: 20px;
  
  .section-title {
    font-size: 18px;
    font-weight: 600;
    color: #333333;
  }
  
  .section-more {
    font-size: 14px;
    color: #409eff;
  }
}

.task-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  
  &.recommend-tasks {
    margin-bottom: 8px;
  }
  
  &.hot-tasks {
    margin-bottom: 8px;
  }
}

.empty-state {
  text-align: center;
  padding: 60px 0;
  
  .empty-text {
    display: block;
    font-size: 16px;
    color: #666666;
    margin-top: 16px;
  }
}

// 响应式适配
@media screen and (min-width: 768px) {
  .index-page {
    padding: 20px;
    max-width: 600px;
    margin: 0 auto;
  }
  
  .search-bar {
    position: relative;
    padding-top: 0;
  }
  
  :deep() {
    .u-swiper {
      .u-swiper-item {
        img {
          height: 200px;
        }
      }
    }
  }
}

// 深色模式适配
:global(.dark-theme) .index-page {
  background-color: #1a1a1a;
  
  .search-bar {
    background-color: #1a1a1a;
    
    .search-input-wrapper {
      background-color: #2a2a2a;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
      
      .search-input {
        color: #ffffff;
        
        &::placeholder {
          color: #666666;
        }
      }
    }
  }
  
  .quick-entry {
        background-color: #2a2a2a;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
        
        .grid-content {
          .entry-icon {
            background-color: #3a3a3a;
            
            &.all-tasks {
              background-color: #1e2b3c;
            }
            
            &.pending-tasks {
              background-color: #1e3c2a;
            }
            
            &.daily-tasks {
              background-color: #3c331e;
            }
            
            &.share-tasks {
              background-color: #3c1e1e;
            }
            
            &.survey-tasks {
              background-color: #2a2d33;
            }
          }
          
          .entry-text {
            color: #999999;
          }
        }
      }
  
  .section-title {
    color: #ffffff !important;
  }
  
  .empty-text {
    color: #999999;
  }

}
</style>
